
// Example: myname $ collate memberA/src some/path/memberB/src another/path/memberC/src java,cpp,c,cs

#include <iostream>
#include <fstream>
#include <vector>
#include <dirent.h>

#define IS_FILE	8
#define IS_DIR	4

using namespace std;



void doCollate(string currPath, string path, ofstream& buffer, vector<string>&);
vector<string> collectExtensions(string fileTypes);
bool checkExtension(string filename, vector<string>& exts);
void collateFile(string path, ofstream& buffer);




int main(int argc, char* argv[]) {

	if (argc < 3) {

		cout << "usage: myname $ collate path/to/folder1 path/to/folder2 exts,eg,java,cs" << endl;
		return 0;

	} else {

		// The final output file
		ofstream outfile("collated.out");

		// Extract the extensions to parse
		vector<string> extensions = collectExtensions(argv[argc-1]);

		// Read till second last
		for (int i=1; i<argc-1; i++) {
	
			string folder = argv[i];

			doCollate("",argv[i], outfile, extensions);

		}

		outfile.close();
	}


	return 0;
}


void doCollate(string currPath, string path, ofstream& buffer, vector<string>& exts) {

	string fullpath = currPath != "" ? currPath + "/" + path : path;

	DIR* dirPtr;
	struct dirent *entry;

	if ( dirPtr = opendir(fullpath.c_str()) ) {

		while ( entry = readdir(dirPtr) ) {

			if ( entry->d_type == IS_FILE && checkExtension(entry->d_name, exts) ) {

				collateFile(fullpath + "/" + entry->d_name, buffer);

			} else if (	entry->d_type == IS_DIR && 
						strcmp(entry->d_name,".") != 0 &&
						strcmp(entry->d_name,"..") != 0
						) {
				// Recurse through subdirs
				doCollate(fullpath, entry->d_name, buffer, exts);
			}
		}
	}
}





vector<string> collectExtensions(string fileTypes) {

	vector<string> exts;

	int start	= 0;
	int length	= 0;

	for (int i=0; i<fileTypes.length() ;i++) {

		if ( fileTypes[i] == ',' ) {
			// Found delimiter
			exts.push_back( fileTypes.substr(start,length) );
			start	= i+1;
			length	= 0;
		}
		
		length++;
	}
	exts.push_back( fileTypes.substr(start,length) );

	return exts;
}



bool checkExtension(string filename, vector<string>& exts) {

	for (int i=0; i< exts.size() ;i++)
		if ( filename.substr( filename.find_last_of(".") + 1) == exts[i] )
	    	return true;

	return false;
}



void collateFile(string path, ofstream& buffer) {

	ifstream infile(path.c_str());

	char line[256];
	infile.getline(line, 256);

	string firstLine = line;

	if (firstLine.substr(0,7) == "@author") {
		// Valid file
		buffer << "/**" << endl;
		buffer << " * author: " << firstLine.substr(8, firstLine.length()-8) << endl;
		buffer << " * origin: " << path << endl;
		buffer << " * any other data " << endl;
		buffer << " */" << endl;

		while (!infile.eof()) {
			infile.getline(line,256);
			buffer << line << endl;
		}

		buffer << endl << endl << endl;

	} else {
		// Do what?
		cout << "Cannot read author: " << path << endl;
	}

}






